<template>
  <!--  采购申请-->
  <div class="content">
    <div style="display: flex">
      <jc-button
        :btn-arr="[bomCost('req:save') && 'newy', 'reload', 'termin', 'terentry', 'remove', 'pass', 'batchFill', 'sub', 'option', 'push', !list.length && 'check']"
        :disab-arr="['using', 'cancel', 'freeze']"
        :fbillno="fbillNo"
        url="tPurRequisition/queryRequistionList"
        @newly="addPriceList"
        @submit="submit(1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @forbidden="using(1)"
        @startUsing="using(2)"
        @termin="termin(1)"
        @termin1="termin(2)"
        @terentry="terentry(1)"
        @terentry1="terentry(2)"
        @del="delApply"
        @refresh="handleGetPurchaseList"
        @toExcel="handleExport"
        @check="check('up')"
        @check1="check('down')"
        @pushDown="isdanjuDialog = true"
        @handleCom1="queryReportForm1(1)"
        @handleCom2="queryReportForm1(2)"
      />
      <el-button
        size="mini"
        style="margin-left: 10px"
        type="primary"
        @click="queryOrder"
      >{{ $t('market.approvalFlow') }}<i v-if="myOrder" class="el-icon-view" /></el-button>
    </div>
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQueryRefuse"
        />
        <el-button
          type="primary"
          class="btn"
          size="mini"
          @click="handleQueryRefuse"
        >
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          :select-data="selectData"
          @seachData="handleQueryRefuse"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        sortable
        card-tab
        table-selection
        get-row-keys="fentryId"
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="handleSelectAll"
        @clickRow="handleDetail"
        @search="handleQueryBomList1"
      >
        <template v-slot:tagSlot="col">
          <el-link type="primary" @click="handleDetail(col.scope.row)">
            {{ col.scope.row.fbillno }}
          </el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <template v-slot:btnState="clo">
          <span v-if="clo.scope.row.fdocumentStatus === ''" />
          <el-tag v-else :type="clo.scope.row.stateColor">
            {{ clo.scope.row.fdocumentStatus }}
          </el-tag>
        </template>
        <template v-slot:billSlot="clo">
          <el-tag v-if="clo.scope.row.fclosestatus==='A'">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else-if="clo.scope.row.fclosestatus==='B'" type="danger">{{ $t('market.closed') }}</el-tag>
        </template>
        <template v-slot:text2Slot="clo">
          <el-tag v-if="clo.scope.row.fstop==='A'">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else-if="clo.scope.row.fstop==='B'" type="danger">{{ $t('btn.termin') }}</el-tag>
        </template>
        <template v-slot:text3Slot="clo">
          <el-tag v-if="clo.scope.row.fentrystop==='A'">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else-if="clo.scope.row.fentrystop==='B'" type="danger">{{ $t('btn.termin') }}</el-tag>
        </template>
        <!-- 状态 -->
        <template v-slot:text4Slot="col">
          <el-tag v-if="col.scope.row.purchaseStatus === '已转'" type="success">{{ $t('market.forwarded') }}</el-tag>
          <el-tag v-if="col.scope.row.purchaseStatus === '未转'" type="danger">{{ $t('market.unconverted') }}</el-tag>
        </template>
      </jc-table>
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :page-sizes="[20,200,500,1000,2000,5000,10000]"
        @pagination="handleGetPurchaseList"
      />
    </div>
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      top="5vh"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX">
          <el-radio v-for="item in receipts" :key="item" :label="item">
            {{ item }}
          </el-radio>
        </el-radio-group>
      </div>
      <hr>
      <div style="text-align: center;">
        {{ $t('market.rule') }}
        <el-input v-model="convert" size="mini" disabled style="width: 178px;margin-bottom: 5px;" />
        <br>
        {{ $t('market.billType') }}
        <el-select
          v-model.trim="fbillTypeId"
          size="mini"
          filterable
        >
          <el-option
            v-for="(item, index) in billTypeData"
            :key="index"
            :label="item.fname"
            :value="item.fid"
          />
        </el-select>
      </div>
      <div style="text-align: center;height: 50px;padding: 20px 0;">
        整单合并:
        <el-checkbox v-model="fmerge" style="line-height: 28px">全部分录行一并下推</el-checkbox><br>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">
          {{ $t('btn.confirm') }}
        </el-button>
      </span>
    </el-dialog>
    <upDown v-if="upDownVis" :msg="cha" :fentryid="fentryData" @client="upDownVis=false" />
  </div>
</template>

<script>
import {
  queryRequistionList,
  deleteRequistion,
  requistionAuSubmit,
  requistionSubmit,
  requistionUnAudit,
  requistionAudit,
  requistionClose,
  requistionUnClose,
  requistionAuStop,
  requistionStop, requistionDtlStop, requistionDtlAuStop
} from '@/api/purchaseManagement/purchaseOrder'
import { toMxAmina } from '@/components/ToMxamineState'
import search from '@/components/Search/index'
import searData from '@/components/Search/mixin'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
import { queryViewItem } from '@/api/marketManage/marketOrder'
import { insertPoorder } from '@/api/purchaseManagement/apply'
export default {
  name: 'ApplyList',
  components: {
    upDown: () => import('@/components/upDown'),
    search,
    filtration,
    jcButton
  },
  mixins: [searData],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      upDownVis: false,
      cha: '',
      fentryData: [],
      fbillNo: '',
      ftype: 49,
      myOrder: false,
      total: 0, // 总条目
      pageNum: 1, // 当前页
      pageSize: 200, // 每页显示多少条数据
      isdanjuDialog: false,
      orderLX: this.$t('menu.purOrderAsi'),
      receipts: [this.$t('menu.purOrderAsi')], // 生产'采购订单']
      fbillTypeId: 159,
      convert: this.$t('market.cgsqzcgdd'),
      fmerge: false,
      billTypeData: [], // 采购订单单据
      // 表头
      tableHeader: [
        { label: this.$t('market.billNo'), type: 'tag', prop: 'fbillno', width: '110' },
        { label: this.$t('market.applyDate'), prop: 'fdate', width: '100' },
        { label: this.$t('market.creator'), prop: 'fcreator', width: '80' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentstatus', width: '80' },
        { label: this.$t('market.businessEnd1'), type: 'text3', prop: 'fentrystop', width: '110' },
        { label: this.$t('market.paezText1'), prop: 'fpaezText', width: '120' },
        { label: this.$t('market.fmodel'), prop: 'fmodel', width: '100' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '120' },
        { label: this.$t('market.productmodel'), prop: 'fproductmodel', width: '120' },
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion', minWidth: '120' },
        { label: this.$t('shop.unit'), prop: 'funit', width: '80' },
        { label: this.$t('shop.state'), type: 'text4', prop: 'purchaseStatus', width: '80' },
        { label: this.$t('market.appQty'), prop: 'freqqty', align: 'right', width: '80' },
        { label: this.$t('market.approveqty'), prop: 'fapproveqty', align: 'right', width: '80' },
        { label: this.$t('market.yipushqty'), prop: 'fpushqty', align: 'right', width: '100' },
        { label: this.$t('market.stockQty'), prop: 'fbaseqty', align: 'right', width: '100' },
        { label: this.$t('market.stockUnit'), prop: 'fstockunit', align: 'right', width: '100' },
        { label: this.$t('market.srcbillcode'), prop: 'fsaleorderno', width: '100' },
        { label: this.$t('market.usedepid'), prop: 'fdeptName', width: '100' },
        { label: this.$t('market.currency2'), prop: 'fsettleCurr', width: '80' },
        { label: this.$t('market.closeState'), type: 'bill', prop: 'fcloseStatus', width: '80' },
        { label: this.$t('market.businessEnd'), type: 'text2', prop: 'fstop', width: '100' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200' }
      ],
      tableData: [],
      // 表格数据
      tableHeader1: [
        { label: this.$t('market.stock2'), prop: 'fstock' },
        { label: this.$t('market.billType'), prop: 'fbilltype' },
        { label: this.$t('market.applicant'), prop: 'fapplicant' },
        { label: this.$t('market.applyDate'), prop: 'fappivalDate' },
        { label: this.$t('market.modifier'), prop: 'fmodifier' },
        { label: this.$t('market.modifyDate'), prop: 'fmodifyDate' },
        { label: this.$t('market.approver'), prop: 'fapprover' },
        { label: this.$t('market.approveDate'), prop: 'fapproveDate' }
      ]
    }
  },
  created() {
    this.handleGetPurchaseList()
    this.purpoorder()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
  },
  methods: {
    // 公共函数
    toExamineFun(api, ev) {
      const DATA = {
        Numbers: this.selectVal,
        EntryIds: ev === 2 ? this.fentryData : [],
        fIds: ev === 2 ? this.fidsData : []
      }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetPurchaseList()
        this.selectVal = []
        this.innerHTM = ''
        res.data && res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 查询本人
    queryOrder() {
      this.myOrder = !this.myOrder
      this.handleGetPurchaseList()
    },
    // 获取列表数据
    async handleGetPurchaseList(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        list: this.list,
        myOrder: this.myOrder ? 'T' : 'F',
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        search: this.searCollData.concat(this.details)
      }
      const { data: res, code, message } = await queryRequistionList(DATA)
      if (code !== 0) {
        this.loading = false
        this.$message.warning(message)
        return
      }
      const { array, total } = res
      this.tableData = array.map(item => {
        return toMxAmina(item)
      })
      this.total = total
      this.loading = false
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '采购申请单列表')
        } else {
          queryRequistionList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return toMxAmina(item)
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '采购申请单列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 搜索
    handleQueryRefuse(ev) {
      this.pageNum = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetPurchaseList(ev.detail)
      } else {
        this.handleGetPurchaseList()
      }
    },
    // 成品 原材料
    handleQueryBomList1(ev) {
      this.searCollData = []
      this.pageNum = 1
      this.searCollData = ev
      this.searchSon = ev
      this.handleGetPurchaseList()
    },
    // 跳转新建申请单
    addPriceList() {
      this.$router.push({ path: '/createApply' })
    },
    // 删除
    delApply() {
      if (this.isDisabled) {
        this.$confirm('请先反审核后再删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        return
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const api = deleteRequistion
          this.toExamineFun(api)
        })
    },
    // 上查、下查
    check(ev) {
      if (this.fentryData.length === 0) return
      this.cha = ev
      this.upDownVis = true
    },
    // 详情
    handleDetail(item) {
      this.$router.push({ path: `/editApply/${item.fid}` })
    },
    // 多选
    handleSelectAll(val) {
      this.val = val
      this.fentryData = []
      this.fidsData = []
      this.selectVal = []
      this.fbillNo = val[0].fbillno
      val.forEach(res => {
        this.fentryData.push(res.fentryId)
        this.fidsData.push(res.fid)
        res.fbillno && this.selectVal.push(res.fbillno)
      })
      this.fidsData = Array.from(new Set(this.fidsData))
    },
    // 提交
    submit(ev) {
      const api = ev === 1 ? requistionSubmit : requistionAuSubmit
      this.toExamineFun(api)
    },
    // 审核
    audit(ev) {
      const api = ev === 1 ? requistionAudit : requistionUnAudit
      this.toExamineFun(api)
    },
    // 关闭
    using(ev) {
      const api = ev === 1 ? requistionClose : requistionUnClose
      this.toExamineFun(api)
    },
    // 终止
    termin(ev) {
      const api = ev === 1 ? requistionStop : requistionAuStop
      this.toExamineFun(api)
    },
    // 明细行终止
    terentry(ev) {
      const api = ev === 1 ? requistionDtlStop : requistionDtlAuStop
      this.toExamineFun(api, 2)
    },
    // 采购订单单据
    async purpoorder() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_PUR_POORDER' })
      this.billTypeData = RES.list
    },
    // 下推采购订单
    pushDownOrder() {
      if (this.orderLX === this.$t('menu.purOrderAsi')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId,
          fmerge: this.fmerge
        }
        insertPoorder(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: '/createPurchase',
              query: {
                id: DATA
              }
            })
            this.isdanjuDialog = false
            this.handleGetPurchaseList()
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      }
    },
    // 套打 连打
    queryReportForm1(ev) {
      const FNUMBER = this.selectVal.join(',')
      if (ev === 1) {
        this.$router.push({ path: `/applyTong1/${FNUMBER}` })
      } else {
        this.$router.push({ path: `/applyLian1/${FNUMBER}` })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;
  .header {
    position: relative;
    .header-name {
      width: 100%;
    }
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
  .price-code {
    &:hover {
      color: #1e9fff;
      text-decoration: underline;
      cursor: pointer;
    }
  }
}
</style>
